import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/home/index.vue'
import UnderConstruction from '../views/common/UnderConstruction.vue'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/stores/user'
import { useLoginStore } from '@/stores/login'
import HouseList from '@/views/house/HouseList.vue'
import { ElMessage } from 'element-plus'

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'Home',
            component: HomeView,
            meta: {
                title: '首页'
            }
        },
        {
            path: '/house',
            name: 'House',
            component: () => import('@/views/house/HouseList.vue'),
            children: [
                {
                    path: '',
                    name: 'HouseList',
                    component: () => import('@/views/house/HouseList.vue')
                },
                {
                    path: 'hot',
                    name: 'HouseHot',
                    component: () => import('@/views/house/HouseHot.vue')
                },
                {
                    path: 'new',
                    name: 'HouseNew',
                    component: () => import('@/views/house/HouseNew.vue')
                }
            ]
        },
        {
            path: '/house/:id',
            name: 'HouseDetail',
            component: () => import('@/views/house/HouseDetail.vue'),
            props: true,
            meta: {
                title: '房源详情'
            }
        },
        {
            path: '/house/map',
            name: 'MapSearch',
            component: () => import('@/views/house/MapSearch.vue'),
            meta: {
                title: '地图找房'
            }
        },
        {
            path: '/agent',
            name: 'Agent',
            component: () => import('@/views/agent/index.vue'),
            meta: {
                title: '经纪人'
            }
        },
        {
            path: '/agent/:id',
            name: 'AgentDetail',
            component: () => import('@/views/agent/AgentDetail.vue'),
            props: true,
            meta: {
                title: '经纪人详情'
            }
        },
        {
            path: '/agent/apply',
            name: 'AgentApply',
            component: () => import('@/views/agent/AgentApply.vue'),
            meta: {
                title: '申请成为经纪人'
            }
        },
        {
            path: '/owner',
            name: 'Owner',
            component: () => import('@/views/owner/index.vue'),
            children: [
                {
                    path: 'sell',
                    name: 'Sell',
                    component: () => import('@/views/owner/HouseSell.vue')
                },
                {
                    path: 'valuation',
                    name: 'Valuation',
                    component: () => import('@/views/owner/Valuation.vue')
                }
            ]
        },
        {
            path: '/about',
            name: 'About',
            component: UnderConstruction,
            children: [
                {
                    path: 'contact',
                    name: 'Contact',
                    component: UnderConstruction
                },
                {
                    path: 'join',
                    name: 'Join',
                    component: UnderConstruction
                }
            ]
        },
        {
            path: '/chat',
            name: 'Chat',
            component: () => import('@/views/chat/index.vue'),
            meta: {
                title: '消息中心',
                requiresAuth: true  // 需要登录才能访问
            }
        },
        {
            path: '/user',
            name: 'User',
            component: () => import('@/views/common/BlankLayout.vue'),
            meta: {
                requiresAuth: true  // 需要登录才能访问
            },
            children: [
                {
                    path: 'favorite',
                    name: 'UserFavorite',
                    component: () => import('@/views/user/Favorite.vue'),
                    meta: {
                        title: '我的收藏',
                        requiresAuth: true
                    }
                },
                {
                    path: 'profile',
                    name: 'UserProfile',
                    component: () => import('@/views/user/Profile.vue'),
                    meta: {
                        title: '个人中心',
                        requiresAuth: true
                    }
                }
            ]
        },
        {
            path: '/test-image-url',
            name: 'TestImageUrl',
            component: () => import('@/views/TestImageUrl.vue'),
            meta: {
                title: '图片URL测试'
            }
        },
        {
            path: '/admin',
            name: 'Admin',
            component: () => import('@/views/admin/index.vue'),
            meta: {
                title: '管理中心',
                requiresAuth: true,
                roles: ['admin', 'agent'] // 需要管理员或经纪人角色
            }
        },
        {
            path: '/admin/houses',
            name: 'AdminHouses',
            component: () => import('@/views/admin/houses/index.vue'),
            meta: {
                title: '房源管理',
                requiresAuth: true,
                roles: ['admin', 'agent']
            }
        },
        {
            path: '/admin/house-assign',
            name: 'AdminHouseAssign',
            component: () => import('@/views/admin/house-assign/index.vue'),
            meta: {
                title: '房源分配',
                requiresAuth: true,
                roles: ['admin', 'agent']
            }
        },
        {
            path: '/admin/view-records',
            name: 'AdminViewRecords',
            component: () => import('@/views/admin/view-records/index.vue'),
            meta: {
                title: '查看记录',
                requiresAuth: true,
                roles: ['admin', 'agent']
            }
        },
        {
            path: '/admin/login-logs',
            name: 'AdminLoginLogs',
            component: () => import('@/views/admin/login-logs/index.vue'),
            meta: {
                title: '登录日志',
                requiresAuth: true,
                roles: ['admin', 'agent']
            }
        },
        {
            path: '/admin/oper-logs',
            name: 'AdminOperLogs',
            component: () => import('@/views/admin/oper-logs/index.vue'),
            meta: {
                title: '操作日志',
                requiresAuth: true,
                roles: ['admin', 'agent']
            }
        },
        {
            path: '/admin/settings',
            name: 'AdminSettings',
            component: () => import('@/views/admin/settings/index.vue'),
            meta: {
                title: '系统设置',
                requiresAuth: true,
                roles: ['admin', 'agent']
            }
        }
    ]
})

// 路由白名单 - 不需要登录就可以访问的路由
const whiteList = ['/', '/login', '/register', '/house', '/agent', '/about', '/chat']

router.beforeEach(async (to, from, next) => {
    const token = getToken()
    const userStore = useUserStore()

    // 设置页面标题
    document.title = to.meta.title ? `${to.meta.title} - 吉居榭` : '吉居榭'

    // 检查是否存在token和过期时间
    const lastActivity = localStorage.getItem('lastActivity')
    
    // 如果有token但最后活动时间超过30分钟，自动登出
    if (token && lastActivity) {
        const now = new Date().getTime()
        const timeout = 30 * 60 * 1000 // 30分钟
        
        if (now - parseInt(lastActivity) > timeout) {
            // 清除token和用户信息
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            localStorage.removeItem('lastActivity')
            
            // 如果当前页面需要认证，显示登录弹窗
            if (to.meta.requiresAuth) {
                const loginStore = useLoginStore()
                loginStore.showLogin()
            }
        }
    }
    
    // 更新最后活动时间
    if (token) {
        localStorage.setItem('lastActivity', new Date().getTime().toString())
    }

    // 检查是否是白名单路由
    if (whiteList.some(path => to.path.startsWith(path))) {
        // 如果是白名单路由，直接放行
        next()
        return
    }

    if (token) {
        if (to.path === '/login') {
            // 已登录且要跳转的页面是登录页
            next({ path: '/' })
        } else {
            // 已登录访问其他页面
            if (!userStore.userInfo) {
                try {
                    await userStore.getInfo()
                    
                    // 检查角色权限
                    if (to.meta.roles && to.meta.roles.length > 0) {
                        const userRoles = userStore.roles || []
                        console.log('用户角色:', userRoles, '路由需要角色:', to.meta.roles)
                        const hasPermission = userRoles.some(role => to.meta.roles.includes(role))
                        
                        if (!hasPermission) {
                            ElMessage.warning('您没有访问权限')
                            next({ path: from.path || '/' })
                            return
                        }
                    }
                    
                    next()
                } catch (error) {
                    console.error('获取用户信息失败:', error)
                    // 如果有存储的用户信息，继续使用
                    if (userStore.userInfo) {
                        next()
                    } else {
                        // 没有用户信息才显示登录弹窗
                        const loginStore = useLoginStore()
                        loginStore.showLogin()
                        next()
                    }
                }
            } else {
                // 检查角色权限
                if (to.meta.roles && to.meta.roles.length > 0) {
                    const userRoles = userStore.roles || []
                    console.log('用户角色:', userRoles, '路由需要角色:', to.meta.roles)
                    const hasPermission = userRoles.some(role => to.meta.roles.includes(role))
                    
                    if (!hasPermission) {
                        ElMessage.warning('您没有访问权限')
                        next({ path: from.path || '/' })
                        return
                    }
                }
                
                next()
            }
        }
    } else {
        // 未登录且不是白名单路由
        if (to.meta.requiresAuth) {
            // 显示登录弹窗而不是跳转
            const loginStore = useLoginStore()
            loginStore.showLogin()
        }
        next()
    }
})

export default router